<?php
class Action{

	// parent object
	private $controller;
	private $JOSN;

	public function __construct(&$controller){
		$this->controller = $controller;
	}


	/**
	 *
	 * Encode $JSON array and flush it to the console
	 */
	function flushJSON(){
		$this->controller->viewData["encodedJSON"] = json_encode($this->JSON);
		$this->controller->load->view("json",$this->controller->viewData);
	}



	/**
	 *
	 * Add an item to the $JSON array
	 * @param String $index
	 * @param String $value
	 */
	function addJSONItem($index, $value){
		$this->JSON[$index] = $value;
	}


	
	// try to find user name in guest name
	function userLogin($flushIfLoggedIn = FALSE){
		$this->addJSONItem("tag", $this->controller->tagModel->getTag("login"));
		$this->addJSONItem("success", 0);

		$email = strtolower($this->controller->input->post("email"));
		$password = $this->controller->input->post("password");

		// see if required inputs are valid
		if($email && $password){

			// checking her info against the database
			$records = $this->controller->simpleDataModel->getRecords(array("EMAIL"=>$email, "ENCRYPTED_PASSWORD"=>md5($password)));
			if(count($records) > 0){

				$record = $records[0];

				// seems her name is on the list
				if($flushIfLoggedIn){
					$this->addJSONItem("success", 1);
					$this->addJSONItem("error", 0);
					$this->addJSONItem("uid", $record->UNIQUE_ID);
					$this->addJSONItem("user", array(
					"id"		=> $record->idUSER,
					"name"		=> $record->NAME,
					"email"		=> $record->EMAIL,
					"created_at"=> $record->CREATED_AT
					));
					// informing UI about the result
					$this->flushJSON();
				}
				return true;
			}else{
				$this->addJSONItem("error", 1);
				$this->addJSONItem("message", $this->controller->lang->line("error_invalid_login"));
				// informing UI about the result
				$this->flushJSON();
				return false;
			}
		}else{
			$this->addJSONItem("error", 1);
			$this->addJSONItem("message", $this->controller->lang->line("error_inputs"));
			// informing UI about the result
			$this->flushJSON();
			return false;
		}
	}

}

